<template>
  <!-- vp-raw的作用是隔绝vitepress样式对当前组件的样式影响 -->
  <div class="vp-raw">
    <vxe-grid ref="VXETableRef" v-bind="gridOptions" @edit-disabled="editDisabledEvent">
      <template #name_edit="{ row }">
        <vxe-input v-model="row.name"></vxe-input>
      </template>
      <template #sex_edit="{ row }">
        <vxe-input v-model="row.sex"></vxe-input>
      </template>
      <template #age_edit="{ row }">
        <vxe-input v-model="row.age"></vxe-input>
      </template>
      <template #address_edit="{ row }">
        <vxe-input v-model="row.address"></vxe-input>
      </template>
      <template #operate_default="{ row }">
        <template v-if="isEditable(row)">
          <a-button @click="() => onCancelEdit(row)">保存</a-button>
          <a-button @click="() => onCancelEdit(row)">取消</a-button>
        </template>
        <template v-else>
          <a-button @click="() => onEdit(row)">编辑</a-button>
        </template>
      </template>
    </vxe-grid>
    <div>
      {{ gridOptions.data }}
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
const VXETableRef = ref()
function onEdit(row) {
  const VXETableInstance = VXETableRef.value
  if (!VXETableInstance) return

  VXETableInstance.setEditRow(row)
}
function onCancelEdit(row) {
  const VXETableInstance = VXETableRef.value
  if (!VXETableInstance) return

  VXETableInstance.clearEdit()
}
function isEditable(row) {
  const VXETableInstance = VXETableRef.value
  if (!VXETableInstance) return

  return VXETableInstance.isEditByRow(row)
}
const gridOptions = reactive({
  border: true,
  showOverflow: true,
  editConfig: {
    trigger: 'click',
    mode: 'row',
  },
  columns: [
    { type: 'seq', width: 50 },
    { field: 'name', title: 'Name', editRender: {}, slots: { edit: 'name_edit' } },
    { field: 'sex', title: 'Sex', editRender: {}, slots: { edit: 'sex_edit' } },
    { field: 'age', title: 'Age', editRender: {}, slots: { edit: 'age_edit' } },
    { field: 'address', title: 'Address', editRender: {}, slots: { edit: 'address_edit' } },
    { field: 'operate', title: '操作', slots: { default: 'operate_default' }, width: 150 },
  ],
  data: [
    { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: 'Man', age: 28, address: 'Shenzhen' },
    { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
    { id: 10003, name: 'Test3', nickname: 'T3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
    { id: 10004, name: 'Test4', nickname: 'T4', role: 'Designer', sex: 'Women', age: 23, address: 'Shenzhen' },
    { id: 10005, name: 'Test5', nickname: 'T5', role: 'Develop', sex: 'Women', age: 30, address: 'Shanghai' },
  ],
})
const editDisabledEvent = () => {
  console.log('禁止编辑')
}
</script>
